package com.example.repository;

import com.example.model.LaundryOrder;
import com.example.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface LaundryOrderRepository extends JpaRepository<LaundryOrder, Long> {
    
    // 根据订单号查找
    Optional<LaundryOrder> findByOrderNumber(String orderNumber);
    
    // 根据客户查找订单
    Page<LaundryOrder> findByCustomer(User customer, Pageable pageable);
    
    // 根据状态查找订单
    Page<LaundryOrder> findByStatus(LaundryOrder.OrderStatus status, Pageable pageable);
    
    // 根据工人查找订单
    Page<LaundryOrder> findByWorker(User worker, Pageable pageable);
    
    // 根据商家查找订单
    Page<LaundryOrder> findByMerchant(User merchant, Pageable pageable);
    
    // 根据时间范围查找订单
    @Query("SELECT o FROM LaundryOrder o WHERE o.createdAt BETWEEN :startDate AND :endDate")
    List<LaundryOrder> findByDateRange(@Param("startDate") LocalDateTime startDate, 
                                      @Param("endDate") LocalDateTime endDate);
    
    // 统计今日订单数量
    @Query("SELECT COUNT(o) FROM LaundryOrder o WHERE o.createdAt >= :startOfDay AND o.createdAt < :endOfDay")
    Long countTodayOrders(@Param("startOfDay") LocalDateTime startOfDay, @Param("endOfDay") LocalDateTime endOfDay);

    // 统计今日收入
    @Query("SELECT COALESCE(SUM(o.finalAmount), 0) FROM LaundryOrder o WHERE o.createdAt >= :startOfDay AND o.createdAt < :endOfDay AND o.paymentStatus = 'PAID'")
    Double getTodayRevenue(@Param("startOfDay") LocalDateTime startOfDay, @Param("endOfDay") LocalDateTime endOfDay);
    
    // 统计待处理订单数量
    @Query("SELECT COUNT(o) FROM LaundryOrder o WHERE o.status IN ('PENDING', 'CONFIRMED')")
    Long countPendingOrders();
    
    // 根据客户ID和状态查找订单
    List<LaundryOrder> findByCustomerIdAndStatus(Long customerId, LaundryOrder.OrderStatus status);
    
    // 查找需要质检的订单
    @Query("SELECT o FROM LaundryOrder o WHERE o.status = 'PROCESSING' AND o.id NOT IN (SELECT qc.order.id FROM QualityCheck qc)")
    List<LaundryOrder> findOrdersNeedingQualityCheck();
}
